package com.uls.lh.service.impl;

import java.util.*;

import com.uls.common.core.domain.entity.SysUser;
import com.uls.hj.vo.TaskCommentVo;
import com.uls.lh.domain.*;
import com.uls.lh.mapper.*;
import com.uls.lh.service.ILhFeeStandardService;
import com.uls.lh.vo.ReportBarchartVo;
import com.uls.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.lh.service.ILhCarrequestService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用车申请管理Service业务层处理
 *
 * @author lh
 * @date 2024-11-11
 */
@Service
public class LhCarrequestServiceImpl implements ILhCarrequestService {
    @Autowired
    private LhCarrequestMapper lhCarrequestMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private LhCarFeeMapper lhCarFeeMapper;
    @Autowired
    private ILhFeeStandardService lhFeeStandardService;
    @Autowired
    private LhFeeStandardMapper lhFeeStandardMapper;
    @Autowired
    private LhDriverinfoMapper lhDriverinfoMapper;
    @Autowired
    private LhCarinfoMapper lhCarinfoMapper;

    @Autowired
    private LhCarScheduleManagementMapper lhCarScheduleManagementMapper;
    /**
     * 查询用车申请管理
     *
     * @param requestId 用车申请管理主键
     * @return 用车申请管理
     */
    @Override
    public LhCarrequest selectLhCarrequestByRequestId(Long requestId) {
        return lhCarrequestMapper.selectLhCarrequestByRequestId(requestId);
    }

    /**
     * 查询用车申请管理列表
     *
     * @param lhCarrequest 用车申请管理
     * @return 用车申请管理
     */
    @Override
    public List<LhCarrequest> selectLhCarrequestList(LhCarrequest lhCarrequest) {
        return lhCarrequestMapper.selectLhCarrequestList(lhCarrequest);
    }

    /**
     * 新增用车申请管理
     *
     * @param lhCarrequest 用车申请管理
     * @return 结果
     */
    @Override
    public int insertLhCarrequest(LhCarrequest lhCarrequest) {
        return lhCarrequestMapper.insertLhCarrequest(lhCarrequest);
    }

    /**
     * 修改用车申请管理
     *
     * @param lhCarrequest 用车申请管理
     * @return 结果
     */
    @Override
    public int updateLhCarrequest(LhCarrequest lhCarrequest) {
        return lhCarrequestMapper.updateLhCarrequest(lhCarrequest);
    }

    /**
     * 批量删除用车申请管理
     *
     * @param requestIds 需要删除的用车申请管理主键
     * @return 结果
     */
    @Override
    public int deleteLhCarrequestByRequestIds(Long[] requestIds) {
        return lhCarrequestMapper.deleteLhCarrequestByRequestIds(requestIds);
    }

    /**
     * 删除用车申请管理信息
     *
     * @param requestId 用车申请管理主键
     * @return 结果
     */
    @Override
    public int deleteLhCarrequestByRequestId(Long requestId) {
        return lhCarrequestMapper.deleteLhCarrequestByRequestId(requestId);
    }


    /**
     * 启动流程
     *
     * @param requestId
     * @param userId
     */
    @Override
    @Transactional
    public int submit(Long requestId, Long userId) {
        LhCarrequest lhCarrequest = lhCarrequestMapper.selectLhCarrequestByRequestId(requestId);

        String processDefiKey = "carrequestProcess";
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 131);  //先写死，是导员的编号
        if (lhCarrequest.getStatus() == 0) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            lhCarrequest.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));
            lhCarrequest.setStatus(1);//状态(0 未提交 , 1 审批中，2 已拒绝，3 已批准）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee("" + userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());

            return lhCarrequestMapper.updateLhCarrequest(lhCarrequest);
        } else {

            Long flowInstantId = lhCarrequest.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());
            lhCarrequest.setStatus(1);//状态(0 未提交 , 1 审批中，2 已拒绝，3 已批准）
            return lhCarrequestMapper.updateLhCarrequest(lhCarrequest);
        }
    }

    @Override
    @Transactional
    public List<LhCarrequest> noFinishTask(Long userId, String processDefiniionKey, LhCarrequest lhCarrequest) {

        List<LhCarrequest> listlhcarrequest = new ArrayList<LhCarrequest>();
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("输入用车申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    lhCarrequest.setFlowInstantId(flowInstanceId);
                    //根据流程id查询学生mapper的方法
                    LhCarrequest lhCarrequests = lhCarrequestMapper.selectLhCarrequestFlowIdOther(lhCarrequest);
                    System.out.println(lhCarrequests);
                    if (lhCarrequests!=null)
                    listlhcarrequest.add(lhCarrequests);
                }

            }
        }


        return listlhcarrequest;
    }

    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {
        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments(""+flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo=new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            SysUser user=sysUserService.selectUserById(Long.parseLong(com.getUserId()));  //查询用户名

            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist= historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if(hist!=null&&hist.size()>0){
                HistoricTaskInstance historicTaskInstance=hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }

            taskCommentVoList.add(taskCommentVo);

        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();

        for(int i= taskCommentVoList.size()-1;i>=0;i--)
        {
            TaskCommentVo temp=taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }

        return taskCommentVoListSort;
    }

    @Override
    @Transactional
    public void completeTask(Long flowInstantId, Integer agree, Long userId, String comment, Long requestId) {
            LhCarrequest lhCarrequest=lhCarrequestMapper.selectLhCarrequestByRequestId(requestId);

            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            // 遍历任务列表
            Map<String, Object> params = new HashMap<String, Object>();

            if (list != null && list.size() > 0) {
                for (Task task : list) {

                    if (task.getName().equals("导员审批")){
                        if (agree==1){
                            params.put("inputUser3", 141);  //固定一个人员4
                            lhCarrequest.setStatus(1);//状态(0 未提交 , 1 审批中，2 已拒绝，3 已批准）
                        }else {
                            lhCarrequest.setStatus(2);
                        }
                        params.put("pass1", agree);  //给流程变量赋值

                    }
                    else if (task.getName().equals("主任审批")){
                        if (agree==1){
                            params.put("inputUser4", 142);  //固定一个人员4
                            lhCarrequest.setStatus(1);//状态(0 未提交 , 1 审批中，2 已拒绝，3 已批准）
                        }else {
                            lhCarrequest.setStatus(2);
                        }
                        params.put("pass2", agree);  //给流程变量赋值

                    } else if (task.getName().equals("院长审批")){
                        if (agree==1){
                            lhCarrequest.setStatus(3);
                            LhCarFee lhCarFee=new LhCarFee();
                            lhCarFee.setRequestId(requestId);
                            LhCarrequest lhCarrequest1=lhCarrequestMapper.selectLhCarrequestByRequestId(requestId);
                            lhCarFee.setCarId(lhCarrequest1.getCarId());
                            lhCarFee.setUsageDate(lhCarrequest1.getStartDate());
                            Date startDate = lhCarrequest1.getStartDate();  // 假设返回 Date 类型
                            Date endDate = lhCarrequest1.getEndDate();      // 假设返回 Date 类型

// 获取两个日期的毫秒差值
                            long diffInMillis = endDate.getTime() - startDate.getTime();

// 将毫秒差值转换为天数（1天 = 86400000毫秒）
                            long daysUsed = diffInMillis / (1000 * 60 * 60 * 24);

// 设置 daysUsed

                            lhCarFee.setDaysUsed(daysUsed);
                            LhFeeStandard lhFeeStandard=lhFeeStandardMapper.selectLhFeeStandardBycarId(lhCarrequest1.getCarId());

                            lhCarFee.setFeePerDay(lhFeeStandard.getFeePerDay());
                            lhCarFee.setFeestandardId(lhFeeStandard.getFeestandardId());
                            Long total=daysUsed * lhFeeStandard.getFeePerDay();
                            lhCarFee.setTotalFee(total);
                            lhCarFeeMapper.insertLhCarFee(lhCarFee);


                            // 获取驾驶员信息
                            Long driverId = lhCarrequest1.getDriverId(); // 假设 LhCarrequest 表中有 driverId 字段
                            if (driverId != null) {
                                LhDriverinfo lhDriverinfo = lhDriverinfoMapper.selectLhDriverinfoByDriverId(driverId);
                                if (lhDriverinfo != null && lhDriverinfo.getStatus().equals("1")) {
                                    // 更新驾驶员状态为 "占用"
                                    lhDriverinfo.setStatus("0"); // 假设 "占用" 是驾驶员状态的值
                                    lhDriverinfoMapper.updateLhDriverinfo(lhDriverinfo);
                                }
                            }

                            Long carId=lhCarrequest1.getCarId();
                            if (carId != null){
                                LhCarinfo lhCarinfo=lhCarinfoMapper.selectLhCarinfoByCarId(carId);
                                if (lhCarinfo != null && lhCarinfo.getStatus().equals(1L)){

                                    lhCarinfo.setStatus(0L);
                                    lhCarinfoMapper.updateLhCarinfo(lhCarinfo);
                                }
                            }

                            // 在审批通过后创建调度记录
                            LhCarScheduleManagement schedule = new LhCarScheduleManagement();
                            schedule.setRequestId(requestId);
                            schedule.setCarId(lhCarrequest1.getCarId());
                            schedule.setDriverId(lhCarrequest1.getDriverId());
                            schedule.setScheduledStartTime(lhCarrequest1.getStartDate());
                            schedule.setScheduledEndTime(lhCarrequest1.getEndDate());
                            schedule.setActualStartTime(lhCarrequest1.getStartDate()); // 假设实际开始时间为申请的开始时间
                            schedule.setActualEndTime(lhCarrequest1.getEndDate()); // 假设实际结束时间为申请的结束时间
                            schedule.setStatus(1); // 调度状态：进行中
                            schedule.setRemarks("审批通过，开始调度");

                            // 插入调度记录
                            lhCarScheduleManagementMapper.insertLhCarScheduleManagement(schedule);




                        }
                        else {
                            lhCarrequest.setStatus(2);
                        }
                        params.put("pass3", agree);  //给流程变量赋值
                    }

                    lhCarrequestMapper.updateLhCarrequest(lhCarrequest);

                    // 添加批注时候的审核人，通常应该从session获取,现在从redis
                    Authentication.setAuthenticatedUserId(userId.toString());
                    // 添加批注
                    taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                    // taskId：任务id
                    taskService.complete(task.getId(), params);

                }

        }

    }


    @Override
    @Transactional
    public List<LhCarrequest> finishTask(Long userId, String processDefiniionKey, LhCarrequest lhCarrequestQuery) {
        List<LhCarrequest> listFinishlhCarrequest=new ArrayList<LhCarrequest>();
        // 创建一个任务查询对象
        //TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance temp : list) {
                if (!temp.getName().equals("输入车辆申请")) {
                    Long flowInstanceId = Long.parseLong(temp.getProcessInstanceId());
                    lhCarrequestQuery.setFlowInstantId(flowInstanceId);
                    //根据流程id查询学生mapper的方法
                    LhCarrequest lhCarrequest = lhCarrequestMapper.selectLhCarrequestFlowIdOther(lhCarrequestQuery);
                    if (lhCarrequest != null){
                        listFinishlhCarrequest.add(lhCarrequest);

                    }

                }

            }
        }

        List<LhCarrequest> listFinishlhCarrequest1 = new ArrayList<>(new HashSet<>(listFinishlhCarrequest));
        return listFinishlhCarrequest1;
    }

    @Override
    public List<ReportBarchartVo> reportcount() {
        List<ReportBarchartVo> result=lhCarrequestMapper.selectCarcount();
        System.out.println(result);
        return result;
    }


}
